package com.tnovoselec.android.favorites.async;

import java.util.concurrent.Callable;

import android.util.Log;

import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.support.DatabaseConnection;
import com.tnovoselec.android.favorites.db.FavoritesDatabaseHelper;

/**
 * Title: Android Framework - Favorites <br />
 * <br />
 * Copyright: Copyright (c) 2011 <br />

 * 
 * Database Initializer is used to create connection on desired database. By
 * default, it gives read/write permission on it.
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0
 * 
 * 
 */
public class DatabaseInitializer implements Callable<Boolean> {

    protected static final String TAG = DatabaseInitializer.class.getSimpleName();

    private final FavoritesDatabaseHelper helper;

    public DatabaseInitializer(FavoritesDatabaseHelper helper) {
	super();
	this.helper = helper;
    }

    /**
     * Creates read/write connection to the database
     */
    @Override
    public Boolean call() throws Exception {
	/* Trigger DB creation/update stuff! */
	ConnectionSource connectionSource = helper.getConnectionSource();
	DatabaseConnection connection = null;
	try {
	    connection = connectionSource.getReadWriteConnection();
	    return Boolean.TRUE;
	} finally {
	    if (connection != null) {
		try {
		    connectionSource.releaseConnection(connection);
		} catch (Exception ex) {
		    Log.e(DatabaseInitializer.TAG, "Database exception: ", ex);
		}
	    }
	}
    }
}
